package com.atguigu.tingshu.search.config;

import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedissonAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisProperties redisProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

     /**
      * @description: Redis客户端的Bean对象
      * @author: baosi
      * @date: 2025/3/25 22:38
      */
    @Bean
    public RedissonClient redissonClient() {
        // 1.给Redisson的配置信息
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort());
        // 2.创建Redisson客户端
        return Redisson.create(config);
    }

     /**
      * @description: 布隆过滤器的bean对象
      * @author: baosi
      * @date: 2025/3/25 22:38
      */
    @Bean
    public RBloomFilter<Object> rBloomFilter(RedissonClient redissonClient) {
        // 如果在Redis中没有这个key,那么会创建一个key,并且将这个key对应的布隆过滤器对象返回 反之 直接将已经创建好的布隆过滤器返回给你。
        RBloomFilter<Object> albumIdBloomFilter = redissonClient.getBloomFilter("albumIdBloomFilter");
        String bloomFilterLockKey = "albumIdBloomFilter:lock";
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(bloomFilterLockKey, "1");
        if (Boolean.TRUE.equals(aBoolean)) {
            // 初始化布隆过滤器
            boolean b = albumIdBloomFilter.tryInit(1000000L, 0.001);  // 利用分布式锁保证分布式布隆的初始化只做一次
            if (b) {
                logger.info("分布式布隆过滤器初始化完，但是数据还未同步进去");
            } else {
                logger.info("分布式布隆过滤器已经初始化完毕");
            }
        }
        return albumIdBloomFilter;
    }
}
